import React, { useState } from 'react';
import { Form, Input, Button, Card, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import './style.css';
import { MOCK_USERS } from '../types/auth';

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const onFinish = async (values: { username: string; password: string }) => {
    setLoading(true);
    try {
      // 模拟登录请求
      const user = MOCK_USERS.find(
        u => u.username === values.username.trim() && u.password === values.password.trim()
      );

      if (user) {
        // 保存登录状态
        localStorage.setItem('adminToken', 'mock-token');
        localStorage.setItem('adminUser', JSON.stringify(user));
        
        message.success('登录成功');
        navigate('/admin/dashboard');
      } else {
        // 检查用户名是否存在
        const userExists = MOCK_USERS.some(u => u.username === values.username.trim());
        if (userExists) {
          message.error('密码错误');
        } else {
          message.error('用户不存在');
        }
      }
    } catch (error) {
      console.error('登录失败:', error);
      message.error('登录失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <Card title="后台管理系统" className="login-card">
        <Form
          name="login"
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入用户名' },
              { whitespace: true, message: '用户名不能包含空格' }
            ]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="用户名"
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码' },
              { whitespace: true, message: '密码不能包含空格' }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              size="large"
            />
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              size="large"
            >
              登录
            </Button>
          </Form.Item>
        </Form>

        <div style={{ marginTop: 16, textAlign: 'center' }}>
          <p style={{ color: '#666' }}>测试账号：</p>
          <p>超级管理员：admin / admin123</p>
          <p>订单管理员：order_admin / order123</p>
          <p>商品管理员：product_admin / product123</p>
        </div>
      </Card>
    </div>
  );
};

export default Login; 